import { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Input, 
  Popconfirm, 
  message,
  Card,
  Descriptions
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  SyncOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  UploadOutlined, 
  FileExcelOutlined,
  TagsOutlined,
  ProfileOutlined,
  HomeOutlined
} from '@ant-design/icons';
import axios from 'axios';
import ShelvesForm from './ShelvesForm';
import ShelvesDetail from './ShelvesDetail';
import ShelvesBarcode from './ShelvesBarcode';
import * as XLSX from 'xlsx';

interface ShelfData {
  id: number;
  name: string;
  code: string;
  boxCount: number;
  skuTypeCount: number;
  skuTotalCount: number;
  remark: string;
}

interface FormValues {
  name: string;
  code: string;
  boxCount?: number;
  skuTypeCount?: number;
  skuTotalCount?: number;
  remark?: string;
}

interface PaginationParams {
  pageIndex: number;
  pageSize: number;
}

interface ApiResponse {
  data: ShelfData[];
  totalCount: number;
  totalPage: number;
  code: number;
  message: string;
}



const ShelvesManagement = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<ShelfData[]>([]);
  const [searchCode, setSearchCode] = useState('');
  const [searchName, setSearchName] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentShelf, setCurrentShelf] = useState<ShelfData | null>(null);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [pagination, setPagination] = useState<PaginationParams>({
    pageIndex: 1,
    pageSize: 10
  });
  const [total, setTotal] = useState(0);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetailId, setCurrentDetailId] = useState<string>('');
  const [barcodeVisible, setBarcodeVisible] = useState(false);
  const [currentBarcodeShelf, setCurrentBarcodeShelf] = useState<{
    id: number;
    name: string;
    code: string;
  } | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState<number[]>([]);

  const fetchShelvesData = async (
    params: PaginationParams = pagination,
    nameParam: string = searchName,
    codeParam: string = searchCode
  ) => {
    setLoading(true);
    try {
      // 使用传入的参数而不是组件状态
      const response = await axios.get('/api/Shelves/QueryShelves', {
        params: { 
          code: codeParam,
          name: nameParam,
          pageIndex: params.pageIndex,
          pageSize: params.pageSize
        }
      });
      
      // 根据后端API的实际返回格式调整
      if (response.data) {
        console.log('API返回数据:', response.data);
        
        // 处理分页数据
        const apiResponse = response.data as ApiResponse;
        const data = Array.isArray(apiResponse.data) ? apiResponse.data : [];
        setTotal(apiResponse.totalCount || 0);
        
        // 确保每条数据都有skuTotalCount字段，如果没有则设为0
        const processedData = data.map((item: unknown) => {
          // 将item转换为Record类型以便访问属性
          const record = item as Record<string, unknown>;
          
          // 检查后端返回的字段名称，可能是不同的命名方式
          const skuTotalCount = 
            'skuTotalCount' in record && record.skuTotalCount !== undefined ? Number(record.skuTotalCount) : 
            'SkuTotalCount' in record && record.SkuTotalCount !== undefined ? Number(record.SkuTotalCount) : 
            'skutotalcount' in record && record.skutotalcount !== undefined ? Number(record.skutotalcount) : 
            'skuCount' in record && record.skuCount !== undefined ? Number(record.skuCount) : 0;
          
          return {
            ...record,
            skuTotalCount: skuTotalCount
          } as unknown as ShelfData;
        });
        
        console.log('处理后的数据:', processedData);
        setDataSource(processedData);
        return Promise.resolve();
      }
    } catch (error) {
      console.error('获取货架数据失败:', error);
      message.error('获取货架数据失败');
      return Promise.reject(error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchShelvesData(pagination, searchName, searchCode);
  }, []);

  const handleTableChange = (page: number, pageSize: number) => {
    const newPagination = {
      pageIndex: page,
      pageSize: pageSize
    };
    setPagination(newPagination);
    fetchShelvesData(newPagination);
  };

  const handleAddShelves = () => {
    setModalType('add');
    setCurrentShelf(null);
    setIsModalVisible(true);
  };

  const handleEditShelves = (record: ShelfData) => {
    setModalType('edit');
    setCurrentShelf(record);
    setIsModalVisible(true);
  };

  const handleDeleteShelves = async (id: number) => {
    try {
      try {
        // 后端API期望在请求体中包含ID，而不是URL参数
        await axios.delete(`/api/Shelves/DeleteShelves`, {
          data: { id: id }, // ID是number类型
          headers: {
            'Content-Type': 'application/json'
          }
        });
      } catch (deleteError) {
        console.warn('标准DELETE请求失败，尝试使用备选方法', deleteError);
        
        // 备选方法：使用POST请求模拟DELETE
        await axios.post(`/api/Shelves/DeleteShelves`, { id: id }, {
          headers: {
            'X-HTTP-Method-Override': 'DELETE',
            'Content-Type': 'application/json'
          }
        });
      }
      
      message.success('删除成功');
      fetchShelvesData();
    } catch (error) {
      console.error('删除货架失败:', error);
      message.error('删除货架失败');
    }
  };

  const handleSearch = () => {
    // 搜索时重置分页到第一页
    const newPagination = {
      ...pagination,
      pageIndex: 1
    };
    setPagination(newPagination);
    
    // 立即显示加载状态
    setLoading(true);
    
    // 立即调用方法刷新页面，使用当前的搜索条件
    fetchShelvesData(newPagination, searchName, searchCode);
    
    if (searchCode || searchName) {
      message.success('搜索中...');
    }
  };

  const handleReset = () => {
    // 先重置搜索条件
    setSearchCode('');
    setSearchName('');
    
    // 重置分页到第一页
    const newPagination = {
      ...pagination,
      pageIndex: 1
    };
    setPagination(newPagination);
    
    // 立即显示加载状态
    setLoading(true);
    
    // 立即调用方法刷新页面，使用空字符串作为搜索条件
    fetchShelvesData(newPagination, '', '');
    
    // 如果有选择的行，也清空选择
    if (selectedRowKeys.length > 0) {
      setSelectedRowKeys([]);
    }
    
    // 清空展开的行
    if (expandedRowKeys.length > 0) {
      setExpandedRowKeys([]);
    }
    
    message.success('已重置并刷新数据');
  };

  const handleFormSubmit = async (values: FormValues) => {
    try {
      // 确保数值字段是数字类型
      const formattedValues = {
        ...values,
        boxCount: typeof values.boxCount === 'number' ? values.boxCount : Number(values.boxCount || 0),
        skuTypeCount: typeof values.skuTypeCount === 'number' ? values.skuTypeCount : Number(values.skuTypeCount || 0),
        skuTotalCount: typeof values.skuTotalCount === 'number' ? values.skuTotalCount : Number(values.skuTotalCount || 0)
      };
      
      console.log('提交的表单数据:', formattedValues);
      
      if (modalType === 'add') {
        // 确保发送的是纯对象，不包含任何特殊字符
        const payload = JSON.parse(JSON.stringify(formattedValues));
        console.log('发送到API的数据:', payload);
        
        await axios.post('/api/Shelves/AddShelves', payload, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        message.success('添加成功');
      } else {
        // 确保发送的是纯对象，不包含任何特殊字符
        const payload = JSON.parse(JSON.stringify({
          ...formattedValues,
          id: currentShelf?.id
        }));
        console.log('发送到API的数据:', payload);
        
        await axios.put('/api/Shelves/UpdateShelves', payload, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        message.success('更新成功');
      }
      setIsModalVisible(false);
      fetchShelvesData();
    } catch (error) {
      console.error('保存货架失败:', error);
      message.error('保存货架失败');
    }
  };

  const handleExportExcel = () => {
    try {
      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      
      // 准备导出数据
      const exportData = dataSource.map((item, index) => ({
        序号: index + 1,
        仓库名称: item.name,
        货架编号: item.code,
        箱子数: item.boxCount,
        SKU种类: item.skuTypeCount,
        SKU数量: item.skuTotalCount,
        备注: item.remark
      }));
      
      // 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      
      // 设置列宽
      const columnWidths = [
        { wch: 6 },  // 序号
        { wch: 15 }, // 仓库名称
        { wch: 15 }, // 货架编号
        { wch: 10 }, // 箱子数
        { wch: 10 }, // SKU种类
        { wch: 10 }, // SKU数量
        { wch: 20 }  // 备注
      ];
      worksheet['!cols'] = columnWidths;
      
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '货架信息');
      
      // 导出Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `货架信息-${new Date().toLocaleDateString()}.xlsx`;
      
      // 模拟点击下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success('导出Excel成功');
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error('导出Excel失败');
    }
  };

  const handleImportExcel = () => {
    // 创建文件输入元素
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.xlsx, .xls';
    fileInput.style.display = 'none';
    
    // 处理文件选择
    fileInput.onchange = (e) => {
      const target = e.target as HTMLInputElement;
      const files = target.files;
      
      if (files && files.length > 0) {
        const file = files[0];
        const reader = new FileReader();
        
        reader.onload = (event) => {
          try {
            const result = event.target?.result;
            const workbook = XLSX.read(result, { type: 'binary' });
            
            // 获取第一个工作表
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            
            // 将工作表转换为JSON
            const jsonData = XLSX.utils.sheet_to_json(worksheet) as Record<string, unknown>[];
            
            // 格式化数据以符合API要求
            const importData = jsonData.map((item) => ({
              name: item['仓库名称']?.toString() || '',
              code: item['货架编号']?.toString() || '',
              boxCount: Number(item['箱子数'] || 0),
              skuTypeCount: Number(item['SKU种类'] || 0),
              skuTotalCount: Number(item['SKU数量'] || 0),
              remark: item['备注']?.toString() || ''
            }));
            
            // 显示导入的数据预览
            console.log('导入的数据:', importData);
            
            // 这里可以添加逻辑将数据发送到后端API
            message.success(`成功导入 ${importData.length} 条数据`);
            
            // 刷新数据
            fetchShelvesData();
            
          } catch (error) {
            console.error('解析Excel文件失败:', error);
            message.error('导入失败，请检查Excel文件格式');
          }
        };
        
        reader.onerror = () => {
          message.error('读取文件失败');
        };
        
        // 以二进制形式读取文件
        reader.readAsBinaryString(file);
      }
    };
    
    // 触发文件选择
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
  };

  const handleViewDetail = (id: number) => {
    setCurrentDetailId(id.toString());
    setDetailVisible(true);
  };

  const handleCloseDetail = () => {
    setDetailVisible(false);
  };

  const handleShowBarcode = (record: ShelfData) => {
    setCurrentBarcodeShelf({
      id: record.id,
      name: record.name,
      code: record.code
    });
    setBarcodeVisible(true);
  };

  const handleCloseBarcode = () => {
    setBarcodeVisible(false);
  };

  const handleRowSelection = (keys: React.Key[]) => {
    setSelectedRowKeys(keys as number[]);
  };

  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一项');
      return;
    }

    try {
      // 依次删除选中的项
      for (const id of selectedRowKeys) {
        await axios.delete(`/api/Shelves/DeleteShelves`, {
          data: { id: id },
          headers: {
            'Content-Type': 'application/json'
          }
        });
      }
      
      message.success(`成功删除 ${selectedRowKeys.length} 项`);
      setSelectedRowKeys([]);
      fetchShelvesData();
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    }
  };

  const handleExpandChange = (expanded: boolean, record: ShelfData) => {
    if (expanded) {
      setExpandedRowKeys([record.id]);
    } else {
      setExpandedRowKeys([]);
    }
  };

  const expandedRowRender = (record: ShelfData) => {
    return (
      <div style={{ padding: '10px 0' }}>
        <Descriptions title="货架详细信息" bordered size="small" column={{ xxl: 4, xl: 3, lg: 3, md: 2, sm: 1, xs: 1 }}>
          <Descriptions.Item label="ID">{record.id}</Descriptions.Item>
          <Descriptions.Item label="仓库名称">{record.name}</Descriptions.Item>
          <Descriptions.Item label="货架编号">{record.code}</Descriptions.Item>
          <Descriptions.Item label="箱子数">{record.boxCount}</Descriptions.Item>
          <Descriptions.Item label="SKU种类">{record.skuTypeCount}</Descriptions.Item>
          <Descriptions.Item label="SKU数量">{record.skuTotalCount}</Descriptions.Item>
          <Descriptions.Item label="备注" span={3}>{record.remark || '-'}</Descriptions.Item>
        </Descriptions>
      </div>
    );
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_: unknown, __: unknown, index: number) => index + 1,
      width: 60,
      align: 'center' as const,
      fixed: 'left' as const
    },
    {
      title: '仓库名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      ellipsis: true,
      render: (text: string) => <span title={text}>{text}</span>
    },
    {
      title: '货架编号',
      dataIndex: 'code',
      key: 'code',
      width: 100,
      ellipsis: true,
      render: (text: string) => <span title={text}>{text}</span>
    },
    {
      title: '箱子数',
      dataIndex: 'boxCount',
      key: 'boxCount',
      width: 80,
      align: 'center' as const,
      sorter: (a: ShelfData, b: ShelfData) => a.boxCount - b.boxCount
    },
    {
      title: 'SKU种类',
      dataIndex: 'skuTypeCount',
      key: 'skuTypeCount',
      width: 80,
      align: 'center' as const,
      sorter: (a: ShelfData, b: ShelfData) => a.skuTypeCount - b.skuTypeCount
    },
    {
      title: 'SKU数量',
      dataIndex: 'skuTotalCount',
      key: 'skuTotalCount',
      width: 80,
      align: 'center' as const,
      sorter: (a: ShelfData, b: ShelfData) => a.skuTotalCount - b.skuTotalCount,
      render: (text: number) => text !== undefined ? text : 0,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150,
      ellipsis: true,
      render: (text: string) => text ? <span title={text}>{text}</span> : '-'
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 280,
      align: 'center' as const,
      render: (record: ShelfData) => (
        <Space size="small" wrap>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            onClick={() => handleEditShelves(record)}
            size="small"
          >
            修改
          </Button>
          <Popconfirm
            title={<>确定要删除此货架吗?<div style={{ fontSize: '12px', color: '#999' }}>删除后数据将无法恢复，请谨慎操作！</div></>}
            onConfirm={() => handleDeleteShelves(record.id)}
            okText="确定"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button 
              danger 
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            type="primary"
            icon={<ProfileOutlined />}
            style={{ backgroundColor: '#13c2c2', borderColor: '#13c2c2' }}
            onClick={() => handleViewDetail(record.id)}
            size="small"
          >
            货架明细
          </Button>
          <Button
            type="primary"
            icon={<TagsOutlined />}
            style={{ backgroundColor: '#faad14', borderColor: '#faad14' }}
            onClick={() => handleShowBarcode(record)}
            size="small"
          >
            标签
          </Button>
        </Space>
      ),
    },
  ];

  // 添加刷新数据的函数
  const handleRefreshData = () => {
    setLoading(true);
    fetchShelvesData(pagination, searchName, searchCode).then(() => {
      message.success('数据已刷新');
    }).catch(() => {
      message.error('刷新数据失败');
    });
  };

  return (
    <div style={{ width: '100%', padding: '0 10px' }}>
      <Card 
        style={{ width: '100%' }} 
        title="货架管理系统" 
        bordered={false}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAddShelves}
            >
              新增
            </Button>
            <Button 
              icon={<UploadOutlined />}
              onClick={handleImportExcel}
            >
              导入货架
            </Button>
            <Button 
              icon={<FileExcelOutlined />} 
              onClick={handleExportExcel}
            >
              导出Excel表格
            </Button>
            <Button 
              icon={<SyncOutlined />} 
              onClick={handleRefreshData}
            >
              刷新数据
            </Button>
          </Space>
        }
      >
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space wrap>
            <Input
              placeholder="输入仓库名称搜索"
              value={searchName}
              onChange={(e) => setSearchName(e.target.value)}
              style={{ width: 200 }}
              allowClear
              prefix={<HomeOutlined />}
              onPressEnter={handleSearch}
            />
            <Input
              placeholder="输入货架编号搜索"
              value={searchCode}
              onChange={(e) => setSearchCode(e.target.value)}
              style={{ width: 200 }}
              allowClear
              prefix={<SearchOutlined />}
              onPressEnter={handleSearch}
            />
            <Button 
              type="primary" 
              onClick={handleSearch}
            >
              搜索
            </Button>
            <Button 
              icon={<SyncOutlined />} 
              onClick={handleReset}
            >
              重置
            </Button>
          </Space>
          
          {selectedRowKeys.length > 0 && (
            <Space>
              <span style={{ marginRight: 8 }}>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              </span>
              <Popconfirm
                title={<>确定要删除选中的 {selectedRowKeys.length} 项吗?<div style={{ fontSize: '12px', color: '#999' }}>删除后数据将无法恢复，请谨慎操作！</div></>}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
                okButtonProps={{ danger: true }}
              >
                <Button danger>批量删除</Button>
              </Popconfirm>
            </Space>
          )}
        </div>

        <Table
          rowKey="id"
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          pagination={{
            current: pagination.pageIndex,
            pageSize: pagination.pageSize,
            total: total,
            showTotal: (total) => `共 ${total} 条`,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: handleTableChange,
            onShowSizeChange: (current, size) => handleTableChange(current, size),
            locale: {
              items_per_page: '条/页',
              jump_to: '跳至',
              jump_to_confirm: '确定',
              page: '页',
              prev_page: '上一页',
              next_page: '下一页',
              prev_5: '向前 5 页',
              next_5: '向后 5 页',
              prev_3: '向前 3 页',
              next_3: '向后 3 页'
            }
          }}
          scroll={{ x: 1200, y: 'calc(100vh - 300px)' }}
          style={{ width: '100%' }}
          bordered
          size="middle"
          rowClassName={(record, index) => index % 2 === 0 ? '' : 'table-row-alternate'}
          rowSelection={{
            selectedRowKeys,
            onChange: handleRowSelection,
            selections: [
              Table.SELECTION_ALL,
              Table.SELECTION_INVERT
            ]
          }}
          expandable={{
            expandedRowRender,
            expandedRowKeys,
            onExpand: handleExpandChange,
            expandRowByClick: true
          }}
          locale={{
            emptyText: '暂无数据',
            filterConfirm: '确定',
            filterReset: '重置',
            selectAll: '全选当页',
            selectInvert: '反选当页',
            selectionAll: '全选所有',
            sortTitle: '排序',
            triggerDesc: '点击降序',
            triggerAsc: '点击升序',
            cancelSort: '取消排序'
          }}
        />
      </Card>

      {/* 货架表单弹窗 */}
      <ShelvesForm
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        onSubmit={handleFormSubmit}
        initialValues={currentShelf || {}}
        type={modalType}
      />
      
      {/* 货架明细弹窗 */}
      <ShelvesDetail
        visible={detailVisible}
        onClose={handleCloseDetail}
        shelfId={currentDetailId}
      />
      
      {/* 货架标签弹窗 */}
      <ShelvesBarcode
        visible={barcodeVisible}
        onClose={handleCloseBarcode}
        shelfData={currentBarcodeShelf}
      />
    </div>
  );
};

export default ShelvesManagement; 